package com._54programer.rabbit;

import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com._54programer.ws.Const;
import com._54programer.ws.Message;
import com._54programer.ws.SID;
import com._54programer.ws.SpringContextUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class Receive {

	//@Autowired
	//private ExecutorService executorService;

	@Autowired
	private SID SSID;

	// 集群分发处理
	@RabbitListener(queues = "#{queue.name}")
	private void CLUSTER_MESSAGE(String message) {
		try {
			if (!StringUtil.isNullOrEmpty(message)) {
				try {
					Message mess = JSON.toJavaObject(JSONObject.parseObject(message), Message.class);

					// 本服指令
					if (mess.getServerId().equals(SSID.ID())) {
						return;
					}

					//异步执行
					//executorService.execute(new Runnable() {
					//	@Override
					//	public void run() {
					//		try {
								// 调用对应业务方法
								Object bean = SpringContextUtils.getBean(Const.CLUSTER_SERVICE);// ClusterMessageHandler
								Class<?> cls = bean.getClass();
								Method method = cls.getMethod("execute", JSONObject.class);
								method.invoke(bean, JSONObject.parseObject(message));
					//		} catch (Exception e) {
					//			log.error("[****集群指令****]异常错误：{}", e.getMessage());
					//		}
					//	}
					//});

				} catch (Exception e) {
					log.error("[****集群指令****]json格式错误：{}", message);
				}
			}
		} catch (Exception e) {
			log.error("[****集群指令****]消息不合法：{}", e);
		}
	}

}
